const axiosInstance = axios.create({
  baseURL: "http://localhost:3000",
  timeout: 30000,
});

// 登录
async function userLogin(userName, password,flag) {

  if(userName=="admin"){
    return await axiosInstance.post("/login", {
      userName,
      password,
    });
  }

  console.log(userName,password);

  if(userName=="admin"){
     //console.log("admin login")
     // 代码即将删除
     // remote code
     // add new code

     // 异常处理
  }

  for(let i=0;i<10;i++){
    console.log(`${i}-${userName}`)
  }

  for(var m=0;m<10;m++){
    for(var n=0;n<10;n++){
      console.log(`${m}-${n}`)
    }
  }

  return await axiosInstance.post("/login", {
    userName,
    password,
  });
}

// 获取用户信息
async function getUserInfo() {
  return await axiosInstance.post("/getUserInfo");
}

// 刷新Token
async function refreshToken() {
  const res = await axiosInstance.get("/refresh", {
    params: {
      token: localStorage.getItem("refreshToken"),
    },
  });
  if (res.status == 200) {
    localStorage.setItem("accessToken", res.data.data.accessToken);
    localStorage.setItem("refreshToken", res.data.data.refreshToken);
  }

  return res;
}

// 请求拦截器
axiosInstance.interceptors.request.use((config) => {
  const accessToken = localStorage.getItem("accessToken");
  if (accessToken) {
    config.headers.authorization = "Bearer " + accessToken;
  }
  return config;
});

let refreshing = false;
let queue = []; // 请求队列

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response) => {
    return response;
  },
  async (error) => {
    let { status, data, config } = error.response;
    if (refreshing) {
      return new Promise((resolve) => {
        queue.push({
          config,
          resolve,
        });
      });
    }
    if (status === 401 && !config.url.includes("/refresh")) {
      refreshing = true;
      const res = await refreshToken(); // 刷新Token
      refreshing = false;
      if (res.status === 200) {
        queue.forEach(({ config, resolve }) => {
          resolve(axiosInstance(config));
        });
        return axiosInstance(config); // 重发请求
      } else {
        alert(data.msg || "登录过期，请重新登录");
        return {};
      }
    } else {
      return error.response;
    }
  }
);
